
package cn.xgj.sfzy.controller;

import cn.xgj.sfzy.util.Result;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName FileController
 * @Description TODO
 * @Author xgj
 * @Date 2024年10月23日 下午3:26
 * @Version 1.0
 */
@RestController
public class FileController {
    private String realPath = "C:\\Users\\Administrator\\Desktop\\ruanjian\\upload";
    //  上传
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return Result.error("没有选中文件");
        }
        String filename = file.getOriginalFilename();
        filename = UUID.randomUUID().toString().replace("-","")+"-"+filename;
//        上传
        file.transferTo(new File(realPath,filename));
        //  上传成功后返回图片的名称
        return Result.success(filename);
    }
    //  预览
    @RequestMapping("/download")
    public void  yuLan(String filename, HttpServletResponse response) throws IOException {
        // 获取文件所属的真实路径
        File file = new File(realPath,filename);
        // 组成字节输出流
        FileInputStream fin = new FileInputStream(file);
        // 设置响应头信息
        response.setHeader("Content-Disposition", "filename="+filename);//预览
        // 组成相应流
        ServletOutputStream out = response.getOutputStream();
        // 拷贝
        IOUtils.copy(fin,out);
        // 释放资源
        out.close();
        fin.close();
    }
}
